package com.lx.algorithm.code.xly3.class08;

import java.util.HashMap;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2022-01-25 15:32:24
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2022-01-25     张李鑫                     1.0         1.0 Version
 */
public class Code01 {
    /**
     * 一种消息接收并打印的结构设计
     * 已知一个消息流会不断地吐出整数 1~N，但不一定按照顺序吐出。如果上次打印的数为 i，
     * 那么当 i+1 出现时，请打印 i+1 及其之后接收过的并且连续的所有数，直到 1~N 全部接收 并打印完，请设计这种接收并打印的结构。
     * 初始时默认i==0
     */

    public class Node {
        public String str;
        public Node next;

        public Node(String str) {
            this.str = str;
        }
    }

    public class Message {
        private HashMap<Integer, Node> head;
        private HashMap<Integer, Node> tail;
        private Integer waitPoint;

        public Message(HashMap<Integer, Node> head, HashMap<Integer, Node> tail) {
            this.head = head;
            this.tail = tail;
            this.waitPoint = 1;
        }


        public void receive(int num, String info) {
            if (num < 1) {
                return;
            }
            Node cur = new Node(info);
            tail.put(num, cur);
            head.put(num, cur);

            if (tail.containsKey(num - 1)) {
                Node node = tail.get(num - 1);
                node.next = cur;
                tail.remove(num - 1);
                head.remove(num);
            }
            if (head.containsKey(num + 1)) {
                Node node = head.get(num + 1);
                cur.next = node;
                tail.remove(num + 1);
                tail.remove(num);
            }

            if (num == waitPoint) {
                print();
            }
        }

        private void print() {
            Node node = head.get(waitPoint);
            while (node != null) {
                System.out.println(node.str);
                waitPoint++;
                node = node.next;
            }
            tail.remove(waitPoint - 1);
        }
    }
}
